package com.frcdi.qms.masterdata.service.impl;

import com.frcdi.qms.common.constant.UserConstants;
import com.frcdi.qms.common.core.domain.TreeSelect;
import com.frcdi.qms.common.core.domain.entity.MaterialType;
import com.frcdi.qms.common.utils.StringUtils;
import com.frcdi.qms.masterdata.mapper.MaterialTypeMapper;
import com.frcdi.qms.masterdata.service.IMaterialTypeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 物料类型Service业务层处理
 *
 * @author frcdi.qms
 * @date 2023-09-08
 */
@Service
public class MaterialTypeServiceImpl implements IMaterialTypeService
{
    private static final Logger log = LoggerFactory.getLogger(MaterialTypeServiceImpl.class);
    @Autowired
    private MaterialTypeMapper materialTypeMapper;

    /**
     * 查询物料类型
     *
     * @param id 物料类型主键
     * @return 物料类型
     */
    @Override
    public MaterialType selectMaterialTypeById(Long id)
    {
        return materialTypeMapper.selectMaterialTypeById(id);
    }

    /**
     * 查询物料类型列表
     *
     * @param materialType 物料类型
     * @return 物料类型
     */
    @Override
    public List<MaterialType> selectMaterialTypeList(MaterialType materialType)
    {
        return materialTypeMapper.selectMaterialTypeList(materialType);
    }

    /**
     * 新增物料类型
     *
     * @param materialType 物料类型
     * @return 结果
     */
    @Override
    public int insertMaterialType(MaterialType materialType)
    {
        MaterialType info = materialTypeMapper.selectMaterialTypeById(materialType.getParentId());
        // 填充修改父级列表数据
        materialType.setAncestors(info.getAncestors() + "," + materialType.getParentId());
        int row = materialTypeMapper.insertMaterialType(materialType);
        return row ;
    }

    /**
     * 修改物料类型
     *
     * @param materialType 物料类型
     * @return 结果
     */
    @Override
    public int updateMaterialType(MaterialType materialType)
    {
        MaterialType newParent = materialTypeMapper.selectMaterialTypeById(materialType.getParentId());
        MaterialType oldresult = materialTypeMapper.selectMaterialTypeById(materialType.getId());
        if (StringUtils.isNotNull(newParent) && StringUtils.isNotNull(oldresult))
        {
            String newAncestors = newParent.getAncestors() + "," + newParent.getId();
            String oldAncestors = oldresult.getAncestors();
            materialType.setAncestors(newAncestors);
            updateMaterialTypChildren(materialType.getId(), newAncestors, oldAncestors);
        }
        int row = materialTypeMapper.updateMaterialType(materialType);
        return row;
    }

    /**
     * 批量删除物料类型
     *
     * @param ids 需要删除的物料类型主键
     * @return 结果
     */
    @Override
    public int deleteMaterialTypeByIds(Long[] ids)
    {
        int row =materialTypeMapper.deleteMaterialTypeByIds(ids);
        return row;
    }

    /**
     * 删除物料类型信息
     *
     * @param id 物料类型主键
     * @return 结果
     */
    @Override
    public int deleteMaterialTypeById(Long id)
    {
        int row = materialTypeMapper.deleteMaterialTypeById(id);
        return row;
    }

    /**
     * 查询物料类型结构信息
     *
     * @param materialType 物料类型信息
     * @return 物料类型信息集合
     */
    @Override
    public List<TreeSelect> selectMaterialTypeTreeList(MaterialType materialType)
    {
        List<MaterialType> materialTypes = this.selectMaterialTypeList(materialType);
        return buildMaterialTypeSelect(materialTypes);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param materialTypes 物料类型列表
     * @return 树结构列表
     */
    @Override
    public List<MaterialType> buildMaterialTypeTree(List<MaterialType> materialTypes)
    {
        List<MaterialType> returnList = new ArrayList<MaterialType>();
        List<Long> tempList = materialTypes.stream().map(MaterialType::getId).collect(Collectors.toList());
        for (MaterialType materialType : materialTypes)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(materialType.getParentId()))
            {
                recursionFn(materialTypes, materialType);
                returnList.add(materialType);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = materialTypes;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param materialTypes 物料类型列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildMaterialTypeSelect(List<MaterialType> materialTypes)
    {
        List<MaterialType> MaterialTypeTrees = buildMaterialTypeTree(materialTypes);
        return MaterialTypeTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }


    /**
     * 递归列表
     */
    private void recursionFn(List<MaterialType> list, MaterialType t)
    {
        // 得到子节点列表
        List<MaterialType> childList = getChildList(list, t);
        t.setChildren(childList);
        for (MaterialType tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<MaterialType> getChildList(List<MaterialType> list, MaterialType t)
    {
        List<MaterialType> tlist = new ArrayList<MaterialType>();
        Iterator<MaterialType> it = list.iterator();
        while (it.hasNext())
        {
            MaterialType n = (MaterialType) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<MaterialType> list, MaterialType t)
    {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 校验物料类型名称是否唯一
     *
     * @param materialType 物料类型
     * @return 结果
     */
    @Override
    public boolean checkMaterialTypeNameUnique(MaterialType materialType) {
        Long typeId = StringUtils.isNull(materialType.getId()) ? -1L : materialType.getId();
        MaterialType info = materialTypeMapper.checkMaterialTypeNameUnique(materialType.getMaterialTypeName(), materialType.getParentId());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != typeId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public boolean hasChildById(Long id) {
        int result = materialTypeMapper.hasChildById(id);
        return result > 0;
    }

    /**
     * 查询物料类型是否存在物料
     *
     * @param id 物料类型ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkMaterialTypeExistMaterial(Long id) {
        int result = materialTypeMapper.checkMaterialTypeExistMaterial(id);
        return result > 0;
    }

    /**
     * 修改子元素关系
     *
     * @param id 被修改的物料类型ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    private void updateMaterialTypChildren(Long id, String newAncestors, String oldAncestors)
    {
        List<MaterialType> children = materialTypeMapper.selectChildrenId(id);
        for (MaterialType child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            materialTypeMapper.updateMaterialTypeChildren(children);
        }
    }
}
